package vn.lumi.smarthome.ui.scene;

import java.util.ArrayList;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.ui.base.MainFragment;
import vn.lumi.smarthome.ulti.ChangeFont;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AddSceneFragmet extends AbstractSceneFragment {

	private static final int LOADER_ID = 0;
	// private static AddSceneFragmet addSceneFragment;
	public static final String ADD_SCENE_FRAGMENT = "addSceneFragment";
	public static final boolean TYPE_EDIT_LIST_FRAGMENT = true;
	public static final boolean TYPE_MAIN_FRAGMENT = false;
	public boolean type = false;

	public static AddSceneFragmet newInstance(int roomId, int floorId,
			String nameRoom, String nameFloor, boolean type) {
		AddSceneFragmet addSceneFragment = new AddSceneFragmet();
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floorId);
		bundle.putInt(ROOM_ID, roomId);
		bundle.putString(MainFragment.NAME_ROOM, nameRoom);
		bundle.putString(MainFragment.NAME_FLOOR, nameFloor);
		bundle.putBoolean(TYPE_FORWARD, type);
		addSceneFragment.setArguments(bundle);
		return addSceneFragment;
	}

	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
		nameRoom = getArguments().getString(MainFragment.NAME_ROOM);
		nameFloor = getArguments().getString(MainFragment.NAME_FLOOR);
		type = getArguments().getBoolean(TYPE_FORWARD);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = super.onCreateView(inflater, container, savedInstanceState);
		btnBack = (Button) view
				.findViewById(R.id.actionbar_setting_activity_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (type == TYPE_EDIT_LIST_FRAGMENT) {
					FragmentManager fm = getActivity()
							.getSupportFragmentManager();
					fm.popBackStack();
				} else {
					FragmentManager fragmentManager = getActivity()
							.getSupportFragmentManager();
					FragmentTransaction transaction = fragmentManager
							.beginTransaction();
					MainFragment mainFragment = MainFragment.newInstance(
							mFloor_id, mRoom_id, MainFragment.SCREEN_SCENE,
							nameRoom, nameFloor);
					transaction.replace(R.id.activity_main_content,
							mainFragment, "main").commit();
				}
			}
		});
		return view;
	}

	@Override
	public void startLoadDeviceList(LoaderCallbacks<Device[]> loaderCallback) {
		Bundle bundle = new Bundle();
		bundle.putInt(AbstractSceneFragment.EXTRA_TYPE, TYPE_CREATE);
		getActivity().getSupportLoaderManager()
				.initLoader(LOADER_ID, bundle, loaderCallback).forceLoad();
	}

	@Override
	public void saveScene() {
		// TODO Auto-generated method stub
		Device[] devices = this.mDeviceListAdapter.getDevices();
		// separate devices
		ArrayList<Device> normalDevices = new ArrayList<Device>();
		ArrayList<Device> RGBs = new ArrayList<Device>();
		for (int i = 0; i < devices.length; i++) {
			if (devices[i].isSelected()) {
				if (devices[i].getType_id() == Device.DEVICE_TYPE_RGB)
					RGBs.add(devices[i]);
				else
					normalDevices.add(devices[i]);
			}
		}

		int[] normalDevicesID = new int[normalDevices.size()];
		int[] normalDevicesState = new int[normalDevices.size()];
		for (int i = 0; i < normalDevices.size(); i++) {
			normalDevicesID[i] = normalDevices.get(i).getId();
			normalDevicesState[i] = normalDevices.get(i).getDeviceState()
					.getValue();
		}

		int[] RGBsID = new int[RGBs.size()];
		int[] RGBsState = new int[RGBs.size()];
		for (int i = 0; i < RGBs.size(); i++) {
			RGBsID[i] = RGBs.get(i).getId();
			RGBsState[i] = RGBs.get(i).getDeviceState().getRGB();
		}

		// put in content values
		ContentValues values = new ContentValues();
		this.newSceneName = this.mEdtName.getText().toString();
		values.put("hour", this.mCurrentHour);
		values.put("minute", this.mCurrentMinute);
		int currentSceneMode = 0;
		if (this.tgbSchedule.isChecked()) {
			currentSceneMode = Scene.SCENE_MODE_AUTO;
		} else {
			currentSceneMode = Scene.SCENE_MODE_NORMAL;
		}
		values.put("Scene mode", currentSceneMode);
		values.put("Scene Name", newSceneName);
		values.put("Room ID", mRoom_id);
		values.put("Normal Devices ID",
				convertIntArrayToString(normalDevicesID));
		values.put("Normal Devices State",
				convertIntArrayToString(normalDevicesState));
		values.put("RGBs ID", convertIntArrayToString(RGBsID));
		values.put("RGBs State", convertIntArrayToString(RGBsState));

		// call back
		getActivity().getApplicationContext().getContentResolver()
				.update(TBL_Scene.CONTENT_URI_CREATE_SCENE, values, null, null);

		// show dialog

		this.dialog = new ProgressDialog(new ContextThemeWrapper(getActivity(),
				R.style.AlertDialogCustom));
		this.dialog.setMessage(this.getString(R.string.txt_saving_scene_in_HC));
		this.dialog.setCancelable(false);
		this.dialog.show();
		// Thay doi font chu cua Dialog
		ChangeFont changeFont = new ChangeFont(getActivity()
				.getApplicationContext());
		TextView textView = (TextView) dialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
				R.string.txt_saving_scene_in_HC, LumiHome.font,
				LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
						.getColor(R.color.greenActionbar));

		// set broadcast receiver
		AddSceneReceiver mAddSceneReceiver = new AddSceneReceiver(dialog);
		IntentFilter filter = new IntentFilter();
		filter.addAction(getActivity().getApplicationContext().getString(
				R.string.vn_lumi_smarthome_create_scene_successful));
		filter.addAction(getActivity().getApplicationContext().getString(
				R.string.vn_lumi_smarthome_create_scene_failed));
		filter.addAction(getActivity().getApplicationContext().getString(
				R.string.vn_lumi_smarthome_create_scene_overload));
		getActivity().registerReceiver(mAddSceneReceiver, filter);
	}

	// @Override
	// public void finish() {
	// // TODO Auto-generated method stub
	// Intent intentMainActivity = new Intent();
	// intentMainActivity.putExtra("Scene", true);
	// intentMainActivity.putExtra("RoomID", mRoomID);
	// setResult(RESULT_OK, intentMainActivity);
	// super.finish();
	// }

	public class AddSceneReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public AddSceneReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			getActivity().unregisterReceiver(this);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.vn_lumi_smarthome_create_scene_successful))) {

				if (type == TYPE_EDIT_LIST_FRAGMENT) {
					FragmentManager fm = getActivity()
							.getSupportFragmentManager();
					fm.popBackStack();
				} else {
					FragmentManager fragmentManager = getActivity()
							.getSupportFragmentManager();
					FragmentTransaction transaction = fragmentManager
							.beginTransaction();
					MainFragment mainFragment = MainFragment.newInstance(
							mFloor_id, mRoom_id, MainFragment.SCREEN_SCENE,
							nameRoom, nameFloor);
					transaction.replace(R.id.activity_main_content,
							mainFragment, "main").commit();
				}

			} else if (intent
					.getAction()
					.equals(context
							.getString(R.string.vn_lumi_smarthome_create_scene_failed))) {
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);
			} else if (intent
					.getAction()
					.equals(context
							.getString(R.string.vn_lumi_smarthome_create_scene_overload))) {
				showCustomDialog(R.string.txt_error, R.string.txt_overloadScene);
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.support.v4.content
	 * .Loader)
	 */
	@Override
	public void onLoaderReset(Loader<Device[]> arg0) {
		// TODO Auto-generated method stub

	}

	public void refresh(int roomId, int floorId, String nameRoom,
			String nameFloor) {
		// TODO Auto-generated method stub
		mFloor_id = floorId;
		mRoom_id = roomId;
		super.nameRoom = nameRoom;
		super.nameFloor = nameFloor;
		// startLoadDeviceList(this);
	}

}
